﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Acms.Bll
{
    public class FileDownload : BaseItem
    {
        protected FileDownload()
        {
        }

        public static FileDownload CreateInstance(File file, User user, System.Net.IPAddress ipAddress)
        {
            if (file == null)
            {
                throw new ArgumentNullException("file", "File cannot be null");
            }
            FileDownload tmp = new FileDownload();
            tmp.FileId = file.Id;
            if (user != null)
            {
                tmp.UserId = user.Id;
            }
            tmp.IPAddress = ipAddress;
            return tmp;
        }

        protected override Acms.SqlDal.Base CreateDal()
        {
            return new Acms.SqlDal.FileDownloadDal();
        }

        protected override void Load(System.Collections.Hashtable table)
        {
            Id = (int)table[Acms.SqlDal.FileDownloadDal.Fields.Id];
            FileId = (int)table[Acms.SqlDal.FileDownloadDal.Fields.FileId];
            UserId = (int?)table[Acms.SqlDal.FileDownloadDal.Fields.UserId];
            try
            {
                IPAddress = System.Net.IPAddress.Parse((string)table[Acms.SqlDal.FileDownloadDal.Fields.IPAddress]);
            }
            catch
            {
            }
            Path = (string)table[Acms.SqlDal.FileDownloadDal.Fields.Path];
            Name = (string)table[Acms.SqlDal.FileDownloadDal.Fields.Name];
            Created = (DateTime)table[Acms.SqlDal.FileDownloadDal.Fields.Created];
        }

        public int Id { get; private set; }
        public int FileId { get; set; }
        public int? UserId { get; set; }
        public System.Net.IPAddress IPAddress { get; set; }
        public string Path { get; set; }
        public string Name { get; set; }
        public DateTime Created { get; private set; }

        public new void Update()
        {
            if (Id == 0)
            {
                Created = DateTime.Now;
            }
            base.Update();
        }

        protected override object SaveChanges(ref object concurencyId, Acms.SqlDal.Base dal)
        {
            int idOut = Id;
            string ipAddress = IPAddress != null ? IPAddress.ToString() : null;

            ((SqlDal.FileDownloadDal)dal).Update(ref idOut, FileId, UserId, ipAddress, Path, Name, Created, ref concurencyId);

            Id = idOut;

            return Id;
        }
    }
}
